#! /usr/bin/env python
import os, sys, cgi, re, time, shutil, traceback, getopt, locale
import tarfile
import subprocess

usage = "python TarDir.py --dir=path --output-dir=path [d,o]"

try:
    opts, args = getopt.getopt(sys.argv[1:], ":d:o:", ["dir=","output-dir="])
except getopt.GetoptError:
    print "getopt error - exiting"
    sys.exit(2)

output_dir = None
for opt, arg in opts:
    if opt in ("-d", "--dir"):
        dir = arg
    elif opt in ("-o", "--output-dir"):
        output_dir = arg

if (output_dir == None):
    output_dir = "."

if vars().has_key('dir'):
    try:
        files = os.listdir(dir)
        for file in files:
            filepath = os.path.join(dir, file)
            if os.path.isdir(filepath):
                print filepath
                compressed_file = output_dir+"/"+file+".tar.gz"
                tar = tarfile.open(compressed_file, "w:gz")
                tar.add(filepath,file)
                tar.close()
                cmd="scp -P 2222 "+compressed_file+" doc4@localhost:~/data/"
                proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
                proc.wait()
                os.remove(compressed_file)
                
        sys.exit(0)
    except Exception,e:
            traceback.print_exc(file=sys.stdout)
            sys.exit(1)
                    
else:
        print "Some options are missing. Usage: %s" % usage
        sys.exit(1)
